<template>
  <canvas ref="pieChart" width="400" height="400"></canvas>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.drawPieChart();
  },
  methods: {
    drawPieChart() {
      const canvas = this.$refs.pieChart;
      const ctx = canvas.getContext('2d');
      const centerX = canvas.width / 2;
      const centerY = canvas.height / 2;
      const radius = Math.min(canvas.width, canvas.height) / 2 * 0.8;

      let total = this.data.reduce((sum, item) => sum + item.value, 0);
      let startAngle = 0;

      this.data.forEach(item => {
        const sliceAngle = (item.value / total) * 2 * Math.PI;

        // 绘制扇形
        ctx.beginPath();
        ctx.fillStyle = item.color;
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
        ctx.fill();

        // 绘制标签
        const midAngle = startAngle + sliceAngle / 2;
        const labelX = centerX + Math.cos(midAngle) * (radius + 20);
        const labelY = centerY + Math.sin(midAngle) * (radius + 20);
        ctx.fillStyle = '#000';
        ctx.textAlign = 'center';
        ctx.fillText(`${item.label} ${item.value} 间`, labelX, labelY);

        startAngle += sliceAngle;
      });
    }
  },
  watch: {
    data: {
      handler() {
        const ctx = this.$refs.pieChart.getContext('2d');
        ctx.clearRect(0, 0, this.$refs.pieChart.width, this.$refs.pieChart.height);
        this.drawPieChart();
      },
      deep: true
    }
  }
}
</script>
